#include<iostream>
#include<pthread.h>
#include<unistd.h>

#define NUM 5
pthread_mutex_t mymutex ; //锁
pthread_cond_t cond ;// 条件变量



//管理线程
void* ctrl(void* args)
{
    while(true)
    {
        //唤醒线程
        std::cout<<"master : begin work"<<std::endl;
        //pthread_cond_signal(&cond);  //唤醒一个
        pthread_cond_broadcast(&cond); //唤醒全部
        sleep(2);
    }
}

//工作线程
void* work(void* args)
{
    int id = *(int*)args;  
    delete (int*)args;
    while(true)
    {
        //等待唤醒
        pthread_cond_wait(&cond,&mymutex);
        std::cout<<"work ["<<id<<"]："<<"is working"<<std::endl;
       
    } 
}

int main()
{   
    //初始化
    pthread_mutex_init(&mymutex,nullptr);
    pthread_cond_init(&cond,nullptr);

    //创建一个管理线程
    pthread_t master;
    pthread_t worker[NUM];
    pthread_create(&master,nullptr,ctrl,(void*)"boss");

    //创建五个工作线程
    for(int i =0 ;i <  NUM ; i++)
    {
        int *id = new int(i);
        pthread_create(worker+i,nullptr,work,(void*)id);
    }

    //等待
    pthread_join(master,nullptr);
    for(int i =0 ;i <  NUM ; i++)
    {
        pthread_join(worker[i],nullptr);
    }

    //销毁
    pthread_mutex_destroy(&mymutex);
    pthread_cond_destroy(&cond);

    return 0;
}
